package com.allm.ai.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * Configures the asynchronous request handling for Spring MVC.
     * This method registers a production-ready thread pool to handle
     * reactive return types like Flux, Mono, Callable, etc.
     *
     * @param configurer The configuration object for async support.
     */
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        // Register our custom AsyncTaskExecutor
        configurer.setTaskExecutor(mvcTaskExecutor());
        // You can also set a default timeout for async requests if needed
        // configurer.setDefaultTimeout(30_000);
    }

    /**
     * Creates a production-ready thread pool for handling asynchronous
     * MVC requests.
     *
     * @return A configured AsyncTaskExecutor.
     */
    @Bean
    public AsyncTaskExecutor mvcTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // --- IMPORTANT: Tune these values for your production environment ---
        // The number of threads to keep in the pool, even if they are idle.
        executor.setCorePoolSize(10);
        // The maximum number of threads to allow in the pool.
        executor.setMaxPoolSize(50);
        // The number of requests to queue before rejecting new ones.
        executor.setQueueCapacity(100);
        // A descriptive name for the threads created by this pool.
        executor.setThreadNamePrefix("mvc-async-");

        executor.initialize();
        return executor;
    }
}
